<template>
	<template v-if="isAlready">
	<draggable v-if="drag" class=" tableDragAreaClass" v-model="widget.props.columns" animation="300"
			   :style="'height:'+ dragAreaHeight+'px;'"
			   item-key="id" :group="{name:'columns'}"
			   @change="dragChange(widget.props.columns)">
		<template #item="{ element }">
			<div class="tableItemClass" @click="dblClick(element)">
				{{ element.label||element.name }}
			</div>
		</template>
	</draggable>
	<div style="width: 100%;">
		<div v-if="!drag" style="float: left;width: 100%; margin-bottom: 3px;margin-top: -15px;">
			<div style="float: right">
				<el-button v-if="model._editFlag" link plain type="primary" @click="btnClick('addAsset')" :loading="loading">添加明细</el-button>
				<el-button v-if="model._editFlag||model._editAssets" link plain type="warning" @click="btnClick('editAssets')" :loading="loading">批量编辑</el-button>
				<el-button v-if="model._editFlag" link plain type="danger" @click="del" :loading="loading">批量移除</el-button>
				<el-button v-if="model._editFlag" link plain type="primary" @click="btnClick('importAssets')" :loading="loading">导入明细</el-button>
<!--				<el-button link plain type="info" @click="exp" :loading="loading">导出</el-button>-->
			</div>
		</div>
		<div style="float: left;width: 100%;">
			<ex-table :id="'dataTable'+widget.id" ref="table" :columns="widget.props.columns" :url="apiUrl" size="small"
					  :drag="drag" :params="{documentId:model.id}" @columnClick="columnClickHandler" :warning-row="model._warningRow"></ex-table>
		</div>
	</div>

	<div v-if="drag" class="innerDrawer">
		<el-drawer v-model="drawerModel" size="130px;" direction="btt" :withHeader="false"
				   style="position: absolute;z-index: -1;">
			<el-form label-width="100" label-position="right" style="padding: 10px 10px 0 10px;">
				<el-row>
					<el-col :span="6" class="colClass">
						<el-form-item label="属性名称">
							{{ currentColumn.name }}  - {{currentColumn.code}}
						</el-form-item>
					</el-col>
					<el-col :span="6" class="colClass">
						<el-form-item label="显示名称">
							<el-input size="small" v-model="currentColumn.label"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6" class="colClass">
						<el-form-item label="存储字段">
							<el-input size="small" v-model="currentColumn.nodeName" placeholder="存储在数据表中的字段编码(驼峰命名规则)"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6" class="colClass">
						<el-form-item label="占用宽度">
							<el-input-number size="small" v-model="currentColumn.width" :min="30"
											 :max="1000"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :span="6" class="colClass">
						<el-form-item label="对齐方式">
							<el-input size="small" v-model="currentColumn.align"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6" class="colClass">
						<el-form-item label="支持排序">
							<el-switch
								v-model="currentColumn.sortable"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
								:active-value="true"
								:inactive-value="false">
							</el-switch>
						</el-form-item>
					</el-col>
					<el-col :span="6" class="colClass">
						<el-form-item label="点击事件">
							<el-input size="small" v-model="currentColumn.click"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6" class="colClass">
						<el-form-item label="固定值">
							<el-input size="small" v-model="currentColumn.fixedValue"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6" class="colClass">
						<el-form-item label="统计值">
							<el-switch
								v-model="currentColumn.summary"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
								:active-value="true"
								:inactive-value="false">
							</el-switch>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-drawer>
	</div>
	</template>
</template>
<script>

import draggable from "vuedraggable";
import ExFormItem from "@/components/exFormItem/index.vue";
import ExTable from "@/components/exTable/index.vue";
import formRule from "@/utils/formRule";



export default {
	name: "wTable",
	components: {ExTable, ExFormItem, draggable},
	props: {
		model: {type: Object, default: {}},
		widget: {type: Object, default: null},
		drag: {type: Boolean, default: false},
	},
	data() {
		return {
			isAlready: false,
			loading:false,
			dragAreaHeight: 40,
			drawerModel: false,
			currentColumn: null,
			apiUrl: null,
			buttonAreaVisible: false,
			showCard:false,
			entity: {},
			click: this.$store.state.click,
		}
	},
	watch: {
		click: {
			handler(val) {
				let clickState = val[this.model.id]
				if(clickState){
					// if(clickState.clear){
					// 	this.$store.dispatch("removeClick", this.model.id);
					// }
					if(clickState.refresh){
						this.$store.dispatch("removeClick", this.model.id);
						this.searchHandler();
					}
				}
			},
			deep: true,
			immediate: false,
		}
	},
	async created() {

		if (!this.widget.props.columns) {
			this.widget.props.columns = [];
		}

		if (!this.drag) {
			if (this.model._btnAuth) {

				if (this.model._btnAuth.editAsset) {
					this.model._warningRow = true;
				} else if (this.model._btnAuth.editAssets) {
					this.model._warningRow = true;
					this.model._editAssets = true;
				} else {
					this.model._warningRow = false;
				}
			} else {
				this.model._warningRow = true;
			}
			for (const column of this.widget.props.columns) {
				let oriColumn = await this.$cache.data.loadColumn(column.columnId);
				Object.assign(column, oriColumn);
				if (column.click) {
					if (this.model._btnAuth) {
						let btns = column.click.split(",");
						let count = 0;
						let permissions = "";
						btns.forEach(btn => {
							if (this.model._btnAuth[btn]) {
								permissions = permissions + "," + btn;
								count++;
							}
						});
						column.permissions = permissions;
						column.buttonAreaVisible = count !== 0;
					}
				}
				formRule.updateColumnFormatter(column);
			}

			this.apiUrl = this.$API.asset.documentDetail.page.url;
			if (!this.model.id) {
				this.apiUrl = null;
			}
		}

		this.isAlready = true;
	},

	methods: {
		//点击其中一个字段时，将当前选中字段替换成点击的字段
		dblClick: function (column) {
			this.currentColumn = column;
			this.drawerModel = true;
		},

		dragChange: function (columns) {
			columns.forEach((item, index) => {
				item.orderWeight = index;
			})
			this.$refs.table.ctrlColumns = columns;
		},
		async searchHandler() {
			let queryParams = {documentId: this.model.id};
			await this.$refs.table.refresh(queryParams);
		},
		columnClickHandler(name,data){
			this.btnClick(name,data);
		},
		//添加
		async btnClick(name, row) {
			let data = {};
			if (name === 'deleteAsset') {
				this.del(this, row);
				return;
			}
			if (name === 'addAsset') {
				data = {documentId: this.model.id};
			}
			if (name === 'editAsset') {
				if (!row) {
					row = this.$refs.table.selectionOne();
				}
				if (!row) {
					return;
				}
				data = row;
			}
			if (name === 'editAssets') {
				let records = this.$refs.table.dataRecords();
				if (records.length === 0) {
					this.$message.warning("没有可以编辑的数据");
					return;
				}
				let selections = this.$refs.table.selections();
				if (selections.length === 0) {
					let confirm = await this.$confirm('请确认是否编辑单据的所有资产明细', '提示', {type: 'warning'}).then(() => {
						return true;
					}).catch(() => {
						return false;
					});
					if(!confirm) return ;
					data = {type:"all",selections:records};
				}else{
					data = {type:"select",selections:selections};
				}
			}
			if (name === 'importAssets') {
				data = {};
			}
			if (name === 'showAsset') {
				if (!row) {
					row = this.$refs.table.selectionOne();
				}
				if (!row) {
					return;
				}
				data = row;
			}
			this.$store.dispatch("addClick", {id: this.model.id, method: name, data: data});
		},
		//批量删除
		del(_this,row) {
			_this = this;
			let selections = [];
			if(row){
				selections.push(row);
			}else{
				selections = _this.$refs.table.selections();
			}
			if (selections.length === 0) {
				_this.$message.warning(_this.$t("common.please_select_data"));
				return;
			}
			_this.$confirm(`确定删除选中的 ${selections.length} 项吗？`, '提示', {
				type: 'warning'
			}).then(async () => {
				_this.loading = true;
				var delarray = [];
				for (let index = 0; index < selections.length; index++) {
					const element = selections[index];
					delarray.push(element.id);
				}
				var res = await _this.$API.asset.documentDetail.deleteByIds.post(delarray);
				if (res.code === 2000) {
					_this.$message.success(_this.$t("code."+res.code));
					await _this.searchHandler();
					_this.$store.dispatch("commit",selections[0].entityName);
				}
				_this.loading = false;
			}).catch(() => {
				_this.loading = false;
			});
		},
		//导出
		async exp(_this,index) {
      let confirm = await this.$confirm('请确认是否执行此操作', '提示', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
      if (!confirm) return;
			_this = this;
			_this.loading = true;
			let queryPrams = _this.$refs.table.queryParams();
			let res = await _this.$API.asset.documentDetail.export.post(queryPrams);
			if (res.code === 2000) {
				await _this.$alert(_this.$t('common.export_request_success'), "提示", {type: 'success'}).catch(()=>{});
			}
			_this.loading = false;
		},

	}
}
</script>
<style>
.tableItemClass {
	cursor: move;
	float: left;
	background: #fff;
	height: 35px;
	text-align: center;
	horiz-align: center;
	border: 1px dashed #e6e6e6;
}

.tableItemClass:hover {
	border-color: rgb(71, 231, 250);
}

.tableDragAreaClass {
	height: 40px;
	background: rgba(243, 149, 95, 0.1);
}
</style>
<script setup>
</script>
